import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.Scanner;

public class TcpEchoSever {
    private ServerSocket severSocket = new ServerSocket();

    public TcpEchoSever(int port) throws IOException {
        severSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        while(true){
            //severSocket 外场负责拉客，只有一个
            //clientSocket 内场负责服务，有且有多个
            Socket clientSocket = severSocket.accept();
            //利用多线程解决一个服务器不能同时服务多个客户端
            //还可以考虑线程池
            Thread thread = new Thread(()->{
                try{
                    //通过这个方法来处理一个连接，以便于代码规范
                    processConnection(clientSocket);
                } catch (IOException e){
                    e.printStackTrace();
                };
            });

            thread.start();
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s,%d]客户端上线\n",clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        //inputStream是从网卡里面读，outputStream是从网卡里写
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            //把字节包装为字符集（更方便），
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true){
                //读响应，算响应，写回响应
                if (!scanner.hasNext()){
                    //读到流的结尾（对端关闭）
                    System.out.printf("[%s,%d]客户端下线!\n",clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                //直接使用Scanner读取一段字符串
                String request = scanner.next();
                //计算响应
                String response = process(request);
                //把响应写给客户端
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s,%d] req:%s,resp:%s\n",clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //只给一个客户端服务，生命周期较短需要关闭
            clientSocket.close();
        }
    }

    private String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoSever tcpEchoClient = new TcpEchoSever(9090);
        tcpEchoClient.start();
    }
}
